package com.carl.zlds.controller.web;

import com.carl.zlds.tool.common.result.Result;
import com.carl.zlds.annotation.Login;
import com.carl.zlds.pojo.vo.StatVO;
import com.carl.zlds.service.IGameAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author carl
 */
@Slf4j
@RestController(value = "web.homeController")
@RequestMapping("/web/home")
@Api(tags = {"客户端 - 主页统计"})
public class HomeController {
    private final IGameAccountService gameAccountService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public HomeController(IGameAccountService gameAccountService) {
        this.gameAccountService = gameAccountService;
    }

    @ApiOperation("用户ip埋点")
    @GetMapping(value = "/track")
    @Login(needToken = false)
    public Result<Void> track(@RequestParam(value = "gameId", required = false, defaultValue = "0") Long gameId,
                              @RequestParam(value = "ip") String ip) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        String key = gameId > 0 ? gameId + ":" + date : date;
        redisTemplate.opsForHyperLogLog().add(key, ip);
        return Result.success();
    }

    @ApiOperation("统计看板")
    @GetMapping(value = "/stat")
    @Login(needToken = false)
    public Result<StatVO> stat(@RequestParam(value = "gameId", required = false, defaultValue = "0") Long gameId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        String key = gameId > 0 ? gameId + ":" + date : date;

        StatVO statVO = gameAccountService.statTotalAccount(gameId);
        Long count = redisTemplate.opsForHyperLogLog().size(key);
        statVO.setTodayVisit(count);
        return Result.success(statVO);
    }
}
